<template>
  <div class="g-con main">
    <div class="left">
      <el-card class="box-card">
        <div
          slot="header"
          class="clearfix card-header"
        >
          <span>{{ t('organizationStructure.Information.t1') }}</span>
          <template v-if="storeLogin.userInfo.isAdmin === '1'">
            <el-button
              v-if="!isEdit"
              type="primary"
              @click="isEdit = true"
            >
              {{ t('organizationStructure.Information.edit') }}</el-button
            >
            <el-button
              type="primary"
              @click="saveChangeInfo()"
              v-else
              >{{ t('organizationStructure.Information.save') }}</el-button
            >
          </template>
        </div>
        <div class="page-divider"></div>
        <el-form>
          <el-row>
            <el-col
              :span="23"
              :offset="1"
            >
              <el-form-item v-if="locale === 'zh-CN'">
                <p v-if="!isEdit">{{ organizationInfo.enterpriseNameCn }}</p>
                <el-input
                  v-else
                  v-model="organizationInfo.enterpriseNameCn"
                  :placeholder="t('organizationStructure.Information.p0')"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <p v-if="!isEdit">{{ organizationInfo.countryName }} - {{ organizationInfo.continentName }}</p>
                <div
                  v-else
                  style="display: flex"
                >
                  <el-select
                    v-model="organizationInfo.countryName"
                    :placeholder="t('register.r1_5')"
                    class="select"
                    style="margin-right: 10px;"
                    :disabled="!organizationInfo.continentName"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="(item, index) in countryOptionList"
                      :key="index"
                      :value="item.id"
                      :label="item.countryName"
                    >
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="organizationInfo.continentName"
                    :placeholder="t('register.r1_6')"
                    class="select"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="(item, index) in continentOptionList"
                      :key="index"
                      :value="item.continentCode"
                      :label="item.continentName"
                    >
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>

              <el-form-item>
                <p v-if="!isEdit">{{ t('organizationStructure.Information.p1') }}: {{ organizationInfo.address }}</p>
                <el-input
                  v-model="organizationInfo.address"
                  :placeholder="t('organizationStructure.Information.p1_placeholder')"
                  v-else
                ></el-input>
              </el-form-item>




              <!-- 船东、船管 -->
              <el-form-item v-if="['05', '06'].includes(customerClassCode)">
                <p v-if="!isEdit">{{ t('organizationStructure.Information.p2') }}: {{ organizationInfo.shipsNum }}</p>
                <el-input
                  v-else
                  v-model="organizationInfo.shipsNum"
                  :placeholder="t('organizationStructure.Information.p2')"
                ></el-input>
              </el-form-item>

              <!-- 修船厂、 制造商、 供应商 、航修/外协 -->
              <el-form-item v-if="!isEdit && ['07', '09', '10', '11'].includes(customerClassCode)">
                <p>
                  {{ t('organizationStructure.Information.p3') }}:
                  <template v-for="n in 5">
                    <img
                      v-if="n <= organizationInfo.ratingStar"
                      src="@/assets/img/icon_shoucang_pre.png"
                      alt=""
                    />
                    <img
                      v-else
                      src="@/assets/img/icon_shoucang_nor.png"
                      alt=""
                    />
                  </template>
                </p>
              </el-form-item>

              <!-- 修船厂 -->
              <template v-if="['07'].includes(customerClassCode)">
                <el-form-item>
                  <p v-if="!isEdit">{{ t('organizationStructure.Information.p4') }}: {{ organizationInfo.dockNum }}</p>
                  <el-input-number
                    v-else
                    :controls="false"
                    :max="5"
                    :min="0"
                    class="input-number"
                    v-model="organizationInfo.dockNum"
                    :placeholder="`${t('organizationStructure.Information.p4')} (≤5)`"
                  ></el-input-number>
                </el-form-item>
                <el-form-item>
                  <div
                    v-if="!isEdit"
                    style="display: grid; grid-template-columns: 130px auto; gap: 10px"
                  >
                    <div>{{ t('organizationStructure.Information.p5') }}:</div>
                    <div>
                      <div
                        v-for="(item, index) in organizationInfo.dockInfoList"
                        :key="index"
                      >
                        {{ item.dockLength }}(M) * {{ item.dockWidth }}(M) * {{ item.dockDeep }}(M)
                      </div>
                    </div>
                  </div>

                  <template v-else>
                    <div style="display: grid; row-gap: 10px">
                      <div
                        class="flexsc nowrap"
                        v-for="(item, index) in organizationInfo.dockInfoList"
                        :key="index"
                      >
                        <el-input
                          v-model="item.dockLength"
                          :placeholder="t('organizationStructure.Information.p5_1')"
                          ><template #suffix>M</template></el-input
                        >
                        <el-input
                          v-model="item.dockWidth"
                          :placeholder="t('organizationStructure.Information.p5_2')"
                          ><template #suffix>M</template></el-input
                        >
                        <el-input
                          v-model="item.dockDeep"
                          :placeholder="t('organizationStructure.Information.p5_3')"
                          ><template #suffix>M</template></el-input
                        >
                      </div>
                    </div>
                  </template>
                </el-form-item>
                <el-form-item>
                  <p v-if="!isEdit">{{ t('organizationStructure.Information.p6') }}: {{ organizationInfo.terminalLength }}(M)</p>
                  <el-input
                    v-else
                    v-model="organizationInfo.terminalLength"
                    :placeholder="t('organizationStructure.Information.p6')"
                    ><template #suffix>M</template></el-input
                  >
                </el-form-item>
                <el-form-item>
                  <p v-if="!isEdit">{{ t('organizationStructure.Information.p13') }}: {{ organizationInfo.businessIntroduce }}</p>
                  <el-input
                    v-else
                    type="textarea"
                    v-model="organizationInfo.businessIntroduce"
                    :placeholder="t('organizationStructure.Information.p13')"
                  ></el-input>
                </el-form-item>
              </template>

              <!-- 制造商 -->
              <template v-if="['09'].includes(customerClassCode)">
                <el-form-item>
                  <p v-if="!isEdit">{{ t('organizationStructure.Information.p7') }}: {{ organizationInfo.ccsNum }}</p>
                  <el-input
                    v-model="organizationInfo.ccsNum"
                    :placeholder="t('organizationStructure.Information.p7')"
                    v-else
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <p v-if="!isEdit">{{ t('organizationStructure.Information.p8') }}: {{ organizationInfo.mainProduct }}</p>
                  <el-input
                    v-else
                    v-model="organizationInfo.mainProduct"
                    :placeholder="t('organizationStructure.Information.p8')"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <p v-if="!isEdit">{{ t('organizationStructure.Information.p9') }}: {{ getDictLabel('enterprise_nature', organizationInfo.enterpriseNature) }}</p>
                  <el-select
                    v-else
                    v-model="organizationInfo.enterpriseNature"
                    :placeholder="t('organizationStructure.Information.p9_1')"
                    class="wp-100"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in dictData.enterprise_nature"
                      :key="item.dictValue"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>

              <!-- 供应商 、航修/外协 、 船员派遣公司-->
              <el-form-item v-if="['10', '11', '14'].includes(customerClassCode)">
                <p v-if="!isEdit">{{ t('organizationStructure.Information.p10') }}: {{ getDictLabel('service_scope', organizationInfo.serviceScope) }}</p>
                <el-select
                  v-else
                  v-model="organizationInfo.serviceScope"
                  :placeholder="t('organizationStructure.Information.p10_1')"
                  class="wp-100"
                  clearable
                  filterable
                >
                  <el-option
                    v-for="item in dictData.service_scope"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <!-- 造船厂 -->
              <template v-if="['08'].includes(customerClassCode)">
                <el-form-item>
                  <p v-if="!isEdit">{{ t('organizationStructure.Information.p11') }}:{{ organizationInfo.shipbuildingCapacity }}</p>
                  <el-input
                    v-model="organizationInfo.shipbuildingCapacity"
                    :placeholder="t('organizationStructure.Information.p11')"
                    v-else
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <p v-if="!isEdit">{{ t('organizationStructure.Information.p12') }}:{{ organizationInfo.shipbuildingType }}</p>
                  <el-input
                    v-model="organizationInfo.shipbuildingType"
                    :placeholder="t('organizationStructure.Information.p12')"
                    v-else
                  ></el-input>
                </el-form-item>
              </template>

              <!-- 船员派遣公司 -->
              <el-form-item v-if="['14'].includes(customerClassCode)">
                <p v-if="!isEdit">{{ t('organizationStructure.Information.p16') }}:{{ organizationInfo.qualifications }}</p>
                <el-input
                  v-else
                  v-model="organizationInfo.qualifications"
                  :placeholder="t('organizationStructure.Information.p16')"
                ></el-input>
              </el-form-item>


              <!-- 主营业务  start             -->
              <el-form-item v-if="['09', '10'].includes(customerClassCode)">
                <p v-if="!isEdit">
                  <div style="display: flex;margin-bottom: 18px">
                    <div style="width: 70px;">
                      {{ t('register.r1_11') }}:
                    </div>

                    <div>
                      <el-tag
                          style="margin-right: 10px;border-radius: 16px;border: none;color:#252628;background:#f5f5f5; padding: 6px 20px;"
                          v-for="(item, index) in selectedLevelList1"
                          :key="index"
                          :type="'danger'">
                        {{item.label}}
                      </el-tag>
                    </div>
                  </div>

                  <div style="display: flex">
                    <div style="width: 120px;">
                      {{ t('register.r1_12') }}:
                    </div>

                    <div>
                      <el-tag
                          style="margin-right: 10px;border-radius: 16px;border: none;color:#252628;background:#f5f5f5; padding: 6px 20px;"
                          v-for="(item, index) in selectedLevelList2"
                          :key="index"
                          :type="''">
                        {{item.label}}
                      </el-tag>
                    </div>
                  </div>

                </p>



                <div v-else>
                  <div

                      style="display: flex"
                  >
                    <div style="position: relative">
                      <div style="position: absolute;top:0px;left: 0px;z-index: 10; margin-left: 10px;color: rgb(96, 98, 102);"
                      >
                        {{ t('register.r1_11') }}
                      </div>
                      <el-select
                          v-model="organizationInfo.level1"
                          class="select select_level1"
                          style="margin-right: 10px;"
                          multiple
                          clearable
                          filterable
                          :placeholder="''"
                          @change="()=>{
                            changeFn()

                          }"
                      >
                        <el-option
                            v-for="(item, index) in levelList1"
                            :key="index"
                            :value="item.id"
                            :label="item.label"
                        >
                        </el-option>
                      </el-select>
                    </div>

                    <div style="position: relative">
                      <div style="position: absolute;top:0px;left: 0px;z-index: 10; margin-left: 10px;color: rgb(96, 98, 102);"
                      >
                        {{ t('register.r1_12') }}
                      </div>

                      <el-select
                          v-model="organizationInfo.level2"
                          :placeholder="''"
                          class="select select_level2"
                          clearable
                          filterable
                          multiple
                      >
                        <el-option
                            v-for="(item, index) in levelList2"
                            :key="index"
                            :value="item.id"
                            :label="item.label"
                        >
                        </el-option>
                      </el-select>
                    </div>




                  </div>
                  <div style="margin-top: 18px;">
                    <div>
                      <el-tag
                          style="margin-right: 10px;border-radius: 16px;border: none;color:#252628;padding: 0px 10px 0px 20px;"
                          v-for="(item, index) in selectedLevelList1"
                          :key="index"
                          :type="'danger'">
                        {{item.label}}
                      </el-tag>
                    </div>

                    <div>
                      <el-tag
                          style="margin-right: 10px;border-radius: 16px;border: none;color:#252628;padding: 0px 10px 0px 20px;"
                          v-for="(item, index) in selectedLevelList2"
                          :key="index"
                          :type="''">
                        {{item.label}}
                      </el-tag>
                    </div>

                  </div>
                </div>




              </el-form-item>
              <!-- 主营业务  end             -->

            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card class="box-card">
        <div
          slot="header"
          class="clearfix card-header"
        >
          <span>{{ t('organizationStructure.Information.t2') }}</span>
          <span
            type="text"
            v-if="storeLogin.userInfo.isAdmin === '1'"
          >
            <el-button
              type="primary"
              @click="uploadDialog = true"
              >{{ t('organizationStructure.Information.upload') }}</el-button
            >
          </span>
        </div>
        <div class="page-divider"></div>
        <ul class="img-list">
          <li
            v-for="(item, index) in queryAlbumList"
            :key="index"
            @click="deleteDialog = true"
          >
            <img
              :src="item"
              alt=""
            />
          </li>
        </ul>
      </el-card>
    </div>
    <div class="right">
      <el-card class="box-card">
        <div
          slot="header"
          class="clearfix card-header"
        >
          <span>{{ t('organizationStructure.Information.t3') }}</span>
          <span
            type="text"
            v-if="storeLogin.userInfo.isAdmin === '1'"
          >
            <el-button
              type="primary"
              @click="openDialog"
              >{{ t('organizationStructure.Information.bt4') }}</el-button
            >
          </span>
        </div>
        <div class="page-divider"></div>
        <div class="list-box">
          <ul
            v-for="item in trendsListData"
            :key="item.id"
            class="item"
          >
            <li class="date-type">
              <!-- <div>
                {{ dateFormat(item.createTime, 2) }}
                <i v-if="item.operateType == 0">{{ t('organizationStructure.operateType1') }}</i>
                <i v-if="item.operateType == 1">{{ t('organizationStructure.operateType2') }}</i>
                <i v-if="item.operateType == 2">{{ t('organizationStructure.operateType3') }}</i>
                <i v-if="item.trendsType == 0">{{ t('organizationStructure.trendsType1') }} </i>
                <i v-if="item.trendsType == 1">{{ t('organizationStructure.trendsType2') }} </i>
                <i v-if="item.trendsType == 2">{{ t('organizationStructure.trendsType3') }} </i>
                <span>——</span>
              </div> -->
            </li>
            <li
              class="flexsb"
              @click="viewDetail(item)"
            >
              <div class="title flexsc">{{ item.trendsTitle }}</div>
              <div class="flexec">
                <img
                  v-if="storeLogin.userInfo.isAdmin === '1'"
                  src="@/assets/img/icon_shanchu_bg.png"
                  alt=""
                  @click="deleteTrendsFn(item)"
                />
              </div>
            </li>
            <div class="content noscrollbar mt-2">
              {{ item.isShowMore ? item.trendsContent : toText(item.trendsContent, 150) }}
              <span
                v-if="item.trendsContent?.length > 150"
                class="show-more"
                @click="item.isShowMore = !item.isShowMore"
              >
                {{ item.isShowMore ? t('blog.b2') : `...${t('blog.b1')}` }}
              </span>
            </div>
            <div class="imglist mt-1 flexsc">
              <el-image
                v-for="(url, index) in item.imgList"
                :src="url"
                :preview-src-list="item.imgListAll"
                :initial-index="index"
                fit="cover"
              />
              <div
                class="more flexcc"
                v-if="item.imgListAll.length > 6"
              >
                {{ `+${item.imgListAll.length - 6}` }}
              </div>
            </div>
            <div class="likeList">
              <img
                :src="url"
                v-for="url in item.likeAvatars"
              />
            </div>
          </ul>
        </div>
        <div class="flexcc mt-3">
          <el-pagination
            layout="prev, pager, next"
            :hide-on-single-page="total <= page.pageSize"
            :total="total"
            v-model:current-page="page.pageNum"
            :page-size="page.pageSize"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </el-card>
    </div>
    <!-- 删除图片 -->
    <el-dialog
      v-model="deleteDialog"
      width="950px"
      class="pre-box"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <h4
            :id="titleId"
            :class="titleClass"
          >
            {{ t('organizationStructure.dlt2') }}
          </h4>
          <img
            src="@/assets/img/icon_guanbi.png"
            @click="close"
            class="close"
          />
        </div>
      </template>
      <div class="pre-img">
        <!-- <img
          :src="chooseImgUrl"
          alt=""
        /> -->
        <el-image
          :src="chooseImgUrl"
          fit="contain"
          style="width: 820px; height: 330px"
        ></el-image>
        <el-button
          type="primary"
          @click="deleteImgFn"
          >{{ t('organizationStructure.dlb1') }}</el-button
        >
      </div>
      <ul class="thumbnail-list">
        <li
          v-for="(item, index) in queryAlbumList"
          :key="index"
          @click="chooseImgUrl = item"
          :class="chooseImgUrl == item ? 'active' : ''"
        >
          <img
            :src="item"
            alt=""
          />
        </li>
      </ul>
    </el-dialog>
    <!-- 发布动态 -->
    <el-dialog
      v-model="trendsDialog"
      :append-to-body="true"
      width="1000px"
      class="dialog-class"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <h4
            :id="titleId"
            :class="titleClass"
          >
            {{ t('organizationStructure.dlt4') }}
          </h4>
          <img
            src="@/assets/img/icon_guanbi.png"
            @click="close"
            class="close"
          />
        </div>
      </template>
      <el-form
        ref="addTrendsFormEl"
        :model="addTrendsForm"
        :rules="addTrendsRules"
      >
        <el-row>
          <el-col
            :span="18"
            :offset="3"
          >
            <el-form-item prop="trendsTitle">
              <el-input
                style="height: 47px"
                :placeholder="t('organizationStructure.Information.p14')"
                v-model.trim="addTrendsForm.trendsTitle"
                :maxlength="100"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            :span="18"
            :offset="3"
          >
            <el-form-item prop="trendsSummary">
              <el-input
                type="textarea"
                :autosize="{ minRows: 6, maxRows: 6 }"
                :resize="'none'"
                :placeholder="t('organizationStructure.Information.p15')"
                v-model.trim="addTrendsForm.trendsSummary"
                :maxlength="500"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            :span="18"
            :offset="3"
          >
            <el-form-item prop="">
              <Uploads
                ref="upload1"
                @change="setFileList"
                :limit="9"
                :listType="'picture-card'"
              ></Uploads>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer flexcc">
          <el-button
            @click="closeFn"
            color="#252628"
            plain
            >{{ t('organizationStructure.cancel') }}</el-button
          >
          <el-button
            type="primary"
            @click="addTrendsFn"
            color="#252628"
            >{{ t('organizationStructure.ok') }}</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!-- 上传图片 -->
    <el-dialog
      v-model="uploadDialog"
      width="800px"
      :show-close="false"
      :close-on-click-modal="false"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <h4
            :id="titleId"
            :class="titleClass"
          >
            {{ t('organizationStructure.dlt1') }}
          </h4>
          <img
            src="@/assets/img/icon_guanbi.png"
            @click="close"
            class="close"
          />
        </div>
      </template>

      <Uploads
        ref="upload2"
        @change="setImgList"
        :listType="'picture-card'"
        :limit="9"
      ></Uploads>

      <template #footer>
        <div class="dialog-footer flexcc">
          <el-button
            @click="uploadDialog = false"
            color="#252628"
            plain
            >{{ t('organizationStructure.cancel') }}</el-button
          >
          <el-button
            type="primary"
            color="#252628"
            @click="addImgFn"
            >{{ t('organizationStructure.ok') }}</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import Uploads from '@/components/Uploads.vue'
import { onMounted, ref, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { getTrendsList, addTrends, deleteTrends, queryAlbum, uploadAlbum, deleteAlbum, getOrganization, changeEnterprise } from '@/service/organizationStructure'
import { uploads } from '@/service/common.js'
import { countryListApi } from '@/service/common.js'
import { dateFormat, toText, openUrl } from '@/utils'
import useLogin from '@/stores/login'
import useDict from '@/hooks/useDict'
import request from '@/utils/request.js'
const { dictData, getDictData, getDictLabel } = useDict()
const storeLogin = useLogin()

const router = useRouter()
const route = useRoute()

const { t, locale } = useI18n()
watch(locale, () => {
  init()
})




const isEdit = ref(false)
const trendsDialog = ref(false)
watch(trendsDialog, (n) => {
  if (!n) {
    addTrendsFormEl.value.resetFields()
  }
})
const uploadDialog = ref(false)
const organizationInfo = ref({
  level1: [],
  level2: []
})

const levelList1 = ref([])

const selectedLevelList1 = computed(() => {
  var matchRes = levelList1.value.filter((item)=>{
    return  (organizationInfo.value.level1 || []).includes(item.id)
  })
  return matchRes
})

const selectedLevelList2 = computed(() => {
  var matchRes = getLevelList2().filter((item)=>{
    return  organizationInfo.value.level2.includes(item.id)
  })
  return matchRes
})

const levelList2 = ref([])
const getLevelList2 = ()=>{
  var res = []
  var matchRes = selectedLevelList1.value
  matchRes.forEach((item)=>{
    res = res.concat(item.children)
  })
  return res
}

const customerClassCode = storeLogin.userInfo.customerClassCode

const copyData = ref([]) //备份数据
const continentOptionList = ref([]) //大洲下拉
const countryOptionList = ref([]) //国家下拉
const openDialog = () => {
  trendsDialog.value = true
}
const deleteDialog = ref(false)
const chooseImgUrl = ref('')
const props = defineProps({
  pageInfo: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

var objectFrom = ref('')
const FileList = ref([])
const ImgList = ref([])
const upload1 = ref(null)
const upload2 = ref(null)

var changeFn = ()=>{

  levelList2.value = getLevelList2()

  // 找到删除的第一级 的二级，全部删除掉
  // organizationInfo.value.level2.forEach((item, index)=>{
  //   organizationInfo.value.level2.splice(index, 1)
  //
  // })
}

const saveChangeInfo = () => {
  organizationInfo.value.id = storeLogin.userInfo.enterpriseId
  var json = {
    "objectFrom": objectFrom.value,
    "shcwBusinessScopes": (()=>{
      var res = [...selectedLevelList1.value.map((item)=>{
        return {
          "firstOption": item.id,
          "secondOption": null,
        }
      }), ...selectedLevelList2.value.map((item)=>{
        return {
          "firstOption": item.parentId,
          "secondOption": item.id,
        }
      })]
      return res
    })(),
  }


  // enterpriseName: null 英文名不修改
  changeEnterprise({ ...organizationInfo.value, enterpriseName: null,
    ...json
  }).then(({ msg }) => {
    ElMessage({
      type: 'success',
      message: msg
    })
    isEdit.value = false
    getOrganizationInfoFn()
    router.go(0)
  })
}
const setImgList = (val) => {
  ImgList.value = val
}
const setFileList = (val) => {
  FileList.value = val
}
const handleUpload = (ref, list) => {
  return new Promise((resolve, reject) => {
    const newList = list.value.filter((item) => item.raw)
    const oldList = list.value.filter((item) => !item.raw).map((item) => item.url)

    if (newList.length) {
      const formData = new FormData()
      newList.forEach((item) => {
        formData.append('files', item.raw)
      })
      uploads(formData).then(({ urls }) => {
        const resultFile = urls.split(',')
        list.value = resultFile.map((item) => {
          return {
            name: item.slice(item.lastIndexOf('/') + 1),
            url: item
          }
        })
        // ref.value.setFileList(list)
        resolve([...oldList, ...resultFile])
      })
    } else {
      resolve(oldList)
    }
  })
}
//发布动态
const addTrendsFormEl = ref(null)
const addTrendsForm = ref({})
const addTrendsRules = ref({
  trendsTitle: [{ required: true, message: t('input_p'), trigger: 'change' }],
  trendsSummary: [{ required: true, message: t('input_p'), trigger: 'change' }]
})
const addTrendsFn = async () => {
  if (!addTrendsFormEl.value) return
  addTrendsFormEl.value.validate(async (valid, fields) => {
    if (valid) {
      const params = {
        ...addTrendsForm.value,
        enterpriseId: storeLogin.userInfo.enterpriseId,
        pushType: 1,
        trendsType: 1,
        createTime: String(new Date().getTime()).substr(0, 10) * 1,
        operateType: 0
      }

      let res = await handleUpload(upload1, FileList)
      if (res.length) {
        params.summaryImage = res.join()
      }

      addTrends(params).then(({ msg }) => {
        ElMessage({
          message: msg,
          type: 'success'
        })
        closeFn()
      })
    }
  })
}
//删除动态
const deleteTrendsFn = (item) => {
  ElMessageBox.confirm(t('popconfirm_del'), '', {
    confirmButtonText: t('confirmText'),
    cancelButtonText: t('cancelText'),
    type: 'warning'
  })
    .then(() => {
      deleteTrends(item.id).then(({ msg }) => {
        ElMessage({
          message: msg,
          type: 'success'
        })
        getTrendsListFn()
      })
    })
    .catch(() => {})
}

//  查看详情
const viewDetail = (item) => {
  if (['0', '1'].includes(item.trendsType)) return
  openUrl('/blogDetail', { id: item.articleId })
}

//获取相册
const queryAlbumList = ref([])
const albumQuery = ref({
  businessType: 2,
  businessId: storeLogin.userInfo.enterpriseId,
  pageSize: 9,
  pageNum: 1
})
const queryAlbumFn = () => {
  queryAlbum(albumQuery.value).then((res) => {
    queryAlbumList.value = res.data
    chooseImgUrl.value = res.data[0]
  })
}

const getScopeOption = ()=>{

  return request({
    url: `/web/enterprise/getScopeOption`,
    method: 'post',
    params:undefined
  }).then((res) => {
    if(res.code === 200){
      objectFrom.value = res.data.objectFrom
      levelList1.value = res.data.list.map((item)=>{
        return {
          id: item.id,
          label: item.name,
          children: item.child.map((subItem)=>{
            return {
              parentId: item.id,
              id: subItem.id,
              label: subItem.name,
            }
          })
        }
      })
    }
  })
}



const closeFn = () => {
  trendsDialog.value = false
  getTrendsListFn()
}
//上传相册
const addImgFn = async () => {
  let data = {
    businessType: 2,
    businessId: storeLogin.userInfo.enterpriseId,
    imagePath: undefined
  }
  let res = await handleUpload(upload2, ImgList)
  if (res.length) {
    data.imagePath = res.join()
  }
  uploadAlbum(data).then(({ msg }) => {
    ElMessage({
      message: msg,
      type: 'success'
    })
    queryAlbumFn()
    getTrendsListFn()
    ImgList.value = []
    uploadDialog.value = false
  })
}
//删除该图片
const deleteImgFn = () => {
  let data = {
    businessType: 2,
    businessId: storeLogin.userInfo.enterpriseId,
    imagePath: chooseImgUrl.value
  }
  ElMessageBox.confirm(t('popconfirm_del'), '', {
    confirmButtonText: t('confirmText'),
    cancelButtonText: t('cancelText'),
    type: 'warning'
  })
    .then(() => {
      deleteAlbum(data).then(({ msg }) => {
        ElMessage({
          message: msg,
          type: 'success'
        })
        deleteDialog.value = false
        queryAlbumFn()
        getTrendsListFn()
      })
    })
    .catch(() => {})
}

// 获取动态
const page = ref({
  pageNum: 1, // 当前页码
  pageSize: 4 // 每页条数
})
const total = ref(0) // 总数
const trendsListData = ref([])
const getTrendsListFn = () => {
  getTrendsList({
    // trendsType: 1,
    pushType: 1,
    enterpriseId: storeLogin.userInfo.enterpriseId,
    ...page.value
  }).then(({ rows, total: t }) => {
    rows.forEach((item) => {
      item.isShowMore = false
      item.imgList = item.summaryImage?.split(',')?.slice(0, 6) || []
      item.imgListAll = item.summaryImage?.split(',') || []
    })
    trendsListData.value = rows
    total.value = t
  })
}
// 分页
const handleCurrentChange = (val) => {
  getTrendsListFn()
}

const getOrganizationInfoFn = () => {
  if (!storeLogin.userInfo.enterpriseId) return
  getOrganization(storeLogin.userInfo.enterpriseId).then(({ data }) => {
    if (!data.dockInfoList) {
      data.dockInfoList = []
    }

    data.level1 = data.firstScopeIdList
    data.level2 = data.secondScopeIdList

    getScopeOption().then(()=>{
      levelList2.value = getLevelList2()
    })




    organizationInfo.value = data
  })
}
watch(
  () => organizationInfo.value.continentName,
  (val, old) => {
    if (val) {
      let filterArr = copyData.value
      countryOptionList.value = filterArr.filter((item) => {
        if (val == item.continentCode) {
          return item
        }
      })
      // formData.value.countryId = undefined
    } else {
      // formData.value.countryId = undefined
      countryOptionList.value = copyData.value
    }
  }
)
watch(
  () => organizationInfo.value.dockNum,
  (val, old) => {
    if (val) {
      organizationInfo.value.dockInfoList = organizationInfo.value.dockInfoList.slice(0, val)
      for (let index = 0; index < val; index++) {
        if (!organizationInfo.value.dockInfoList[index]) {
          organizationInfo.value.dockInfoList[index] = {}
        }
      }
    }
  }
)

const init = () => {
  getDictData('service_scope')
  getDictData('enterprise_nature')
  getTrendsListFn()
  queryAlbumFn()
  getOrganizationInfoFn()
  countryListApi().then((res) => {
    countryOptionList.value = res.data
    res.data.map((item) => {
      if (!continentOptionList.value.some((child) => child.continentName === item.continentName)) {
        continentOptionList.value.push(item)
      }
    })
    copyData.value = res.data
  })


  getScopeOption()


}
onMounted(() => {
  init()
})
</script>
<style lang="scss">
.select_level1, .select_level2{
  .el-select__tags{
    display: none !important;
  }
}
</style>
<style scoped lang="scss">

.pre-box {
  .pre-img {
    width: 100%;
    padding: 50px;
    position: relative;
    border-bottom: 2px solid black;

    img {
      width: 820px;
      height: 330px;
      border: 1px solid;
    }

    button {
      position: absolute;
      right: 20px;
      top: 10px;
    }
  }

  .thumbnail-list {
    width: 100%;
    height: 140px;
    display: flex;
    justify-content: center;
    padding: 20px 0px;

    // background: rgb(245,245,245);
    li {
      width: 110px;
      height: 110px;

      cursor: pointer;

      &:not(:last-child) {
        margin-right: 20px;
      }

      img {
        width: 100%;
        height: 100%;
        border-radius: 10px;
        border: 1px solid;
      }
    }

    .active {
      border: 2px solid rgb(202, 42, 2);
      border-radius: 10px;
    }
  }
}

.main {
  display: flex;

  .left {
    width: 410px;
    margin-right: 20px;
    min-height: 200px;

    .card-header {
      display: flex;
      line-height: 40px;
      font-size: 18px;

      font-weight: bold;
      color: #252628;

      span:first-child {
        flex: 9;
        font-size: 20px;
      }

      button {
        margin: auto;
      }
    }

    .box-card {
      min-height: 316px;
      margin-bottom: 30px;

      .img-list {
        width: 100%;
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 10px;

        li {
          width: 100%;
          height: 110px;
          margin-top: 10px;
          cursor: pointer;

          img {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }

  .right {
    flex: 5;
    min-height: 200px;

    .card-header {
      display: flex;
      line-height: 40px;
      font-size: 18px;

      font-weight: bold;
      color: rgba(202, 42, 2, 1);

      span:first-child {
        flex: 9;
        font-size: 20px;
      }

      button {
        margin: auto;
      }
    }

    .box-card {
      padding-left: 20px;

      .list-box {
        width: 100%;
        padding-right: 10px;

        .item {
          min-height: 181px;
          margin-bottom: 23px;
          background: rgba(245, 245, 245, 1);
          padding: 20px;

          // padding-right: 10px;
          .date-type {
            width: 100%;
            font-size: 14px;

            font-weight: 400;
            color: #9d9fa5;
            display: flex;
            justify-content: space-between;
            line-height: 40px;

            span {
              color: #ca2a02;
            }

            i {
              font-style: normal;
            }

            img {
              cursor: pointer;
            }
          }

          .title {
            font-size: 20px;
            font-weight: bold;
            color: #252628;
            cursor: pointer;
          }

          .content {
            font-size: 14px;
            color: #6a6973;
            white-space: pre-line;
            overflow-wrap: break-word;
            .show-more {
              color: #000;
              cursor: pointer;
            }
          }

          .imglist {
            .el-image {
              width: 100px;
              height: 100px;
              background: #eaebec;
              margin-right: 14px;
            }

            .more {
              width: 100px;
              height: 100px;
              background: rgba(0, 0, 0, 0.3);
              margin-left: -114px;
              position: relative;
              z-index: 9;
              color: #fff;
              font-size: 28px;
              pointer-events: none;
            }
          }

          .likeList {
            img {
              width: 30px;
              height: 30px;
              background: #d99993;
              border-radius: 4px;
              margin-right: 10px;
            }
          }
        }
      }
    }
  }
}

.divider {
  width: 100%;
  height: 3px;
  background: black;
  margin-bottom: 36px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.page-divider {
  width: 100%;
  height: 2px;
  background: black;
  margin-bottom: 10px;
  margin-top: 10px;
}

.input-number {
  width: 100%;
  :deep(.el-input__inner) {
    text-align: left;
  }
}
</style>
